I wrote some code in order to get a file name from the user at the terminal. I tried using realloc but there is an error in memory management that I do not understand. I am not sure if I am incorrectly terminating the string, or if there is another error that I cannot see with my limited C experience. Could anyone instruct me on what errors I have made?
Code:
<stdio.h>
#include <stdlib.h>
#define CHUNK 4
char *file_name;
char *get_file_name(void) {
char *line = NULL;
char *tmp = NULL;
int char_input = 0;
size_t size = 0, index = 0;
size = CHUNK;
printf("Please enter the file name: \n");
while(char_input != '\n' && char_input != EOF) {
char_input = getc(stdin);
if(size <= index) {
size += CHUNK;
tmp = realloc(line, size);
if (!tmp) {
free(line);
line = NULL;
break;
}
line = tmp;
}
line[index] = char_input;
index++;
}
line[index] = '\0';
return line;
}
int main(void) {
file_name = get_file_name();
printf("%s", file_name);
return 0;
}